<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
ini_set('max_execution_time', '0');
/*******************
 ***  处理外部速卖通接口订单数据
 ***  "http://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/"
 *** 2017/06/05
 **********/
class Aliexpressdata
{
    private $urlApi = "http://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/";
    public function __construct()
    {
        $this->CI =& get_instance();
        $this->db = $this->CI->load->database('default', TRUE);
        $this->CI->load->library('amazondata');
		$this->CI->load->model('Function_m','fun');
        //$this->CI->load->model("Aliexpress_m",'aliexpress');
    }
    public function doInsertOrderRecords(){
        //插入数据库必须要有一个标记，用于确定到底是哪一个店铺的订单数据
        $sql = "SELECT * FROM d_shop WHERE platfromname = 'aliexpress' and agent_visit=0   ORDER BY id DESC ";
        $rs = $this->db->query($sql)->result_array();
        $time = time();
        //最后十天之内更换refresh_token
        $expireTime = $time+10*60*60*24;
        foreach ($rs as $k => $v) {
            //判断refresh_token是否在过期前十天之内，如果在则更新refresh_token以及过期时间
            if($v['refresh_timeout']&&(int)$v['refresh_timeout']< $expireTime){
                //获取新的refresh_token，并更新
                $rs_refresh = $this->getRefreshToken($v['refresh_token'],$v['access_token'],$v['appkey'],$v['appsecret']);
			
                if(!empty($rs_refresh['refresh_token'])){
                    $arr_refresh['refresh_token'] = $rs_refresh['refresh_token'];
                    $arr_refresh['access_token'] = $rs_refresh['access_token'];
                    $arr_refresh['refresh_timeout'] = $rs_refresh['refresh_token_timeout'];
                    $arr_refresh['access_timeout'] = $rs_refresh['expires_in']+time();
                    $this->db->where('id',$v['id']);
                    $this->db->update('d_shop',$arr_refresh);
                    $v['refresh_token'] = $rs_refresh['refresh_token']; //使用的新口令
                }else{
                    echo "长期令牌获取失败";
                    continue;
                    //exit;
                }
            }
            if($v['access_timeout']){
            }else{
                echo "未知错误";
                echo "<br/>";
                continue;
            }
            //判断生存期限仅十个小时的access_token是否过期，过期则通过refresh_token重新获取
            if ($time >(int)$v['access_timeout']) {
					
                //重新获取access_token，并更新 获取数据以最新access_token为准，不然获取不到
                $arr_access_token = $this->getAccessToken($v['refresh_token'], $v['appkey'], $v['appsecret']);
                $data['access_timeout'] = time() + $arr_access_token['expires_in'];
                $data['access_token'] = $arr_access_token['access_token'];
                $this->db->where('id', $v['id']);
                $this->db->update('d_shop',$data);
                $v['access_token'] = $data['access_token'];
            }
            //获取相关数据并对相关表操作
            $order_rs = $this->getOrderList($v['appkey'],$v['appsecret'],$v['access_token'],$v['id'],$v['name'],$v['updateoper']);
            //执行对正式数据库表操作6/8
            $this->doInsertOrderData($v['id']);
        }
    }
    //更新db_order_list db_order_sell
    private function doInsertOrderData($shopid){
        $sql_ordertmp = "SELECT * FROM db_aliexpress_ordertmp WHERE shopid = '$shopid' AND orderStatus = 'WAIT_SELLER_SEND_GOODS' AND flag = 0 GROUP BY orderId ";
        $rs_ordertmp = $this->db->query($sql_ordertmp)->result_array();
            if(count($rs_ordertmp)>0){
                //更新db_order_list
                foreach($rs_ordertmp as $k=>$v){
                        $sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['orderId']}' ";
                        $rs_order = $this->db->query($sql_order)->row_array();
                        if($rs_order){
                            continue;
                        }
                        $arr_order_list['order_sn'] = $this->CI->amazondata->getNo('Aliexpress',$v['orderId']);//生成订单序号
                        $arr_order_list['dates']  = date("Y-m-d"); //当天日期 判断order_sn使用
                        $arr_order_list['ordertime']  = $v['gmtCreate']; //订单日期时间
                        $arr_order_list['order_source']  = "正常订单"; //默认
                        $arr_order_list['customerid']  = $v['buyerSignerFullname']; //客户id
                        $arr_order_list['consignee']  =$v['contactPerson']; //收货人
                        $arr_order_list['country']  = $v['country']; //国家
                        $arr_order_list['country_code']  = $v['country_code']; //国家
                        $arr_order_list['country_cn']  = $v['country_cn'];
                        $arr_order_list['province']  = $v['province'];
                        $arr_order_list['city']  = $v['city'];
                        if($v['address']){
                            $arr_order_list['address']  = $v['address'];
                            $arr_order_list['address2']  = $v['address2'];
                        }else{
                            $arr_order_list['address']  = $v['address2'];
                            //$arr_order_list['address2']  = "";
                        }

                        $arr_order_list['zipcode']  = $v['zip'];
                        $arr_order_list['tel']  = $v['phoneNumber'];
                        $arr_order_list['mobile']  = $v['mobileNo'];
                        $arr_order_list['shopid']  = $v['shopid']; //店铺id
                        $arr_order_list['shopname']  = $v['shopname'];
                        $arr_order_list['shopoper']  = $v['shopoper'];//店铺负责人
						$rshop = $this->db->get_where("d_shop","name='".$v["shopname"]."'")->result_array();
						$arr_order_list['platformID']  = $rshop[0]['platfrom'];//平台
						$exchange=$this->db->get_where("d_moneyrate","name='".$v["currencyCode"]."'")->result_array();
						$arr_order_list['moneyrate']  = $exchange[0]["rate"];//汇率
						
                        $arr_order_list['moneytype']  = $v['currencyCode'];//货币类型
                        $arr_order_list['tradeid']  = $v['orderId']; //交易单号

                        //$arr_order_list['goods_originask']  = $v['goods_originask']; //订单金额
                        //$arr_order_list['goods_amount']  = $v['goods_amount'];
                        //使用实际付款金额来计算
                        $arr_order_list['goods_originask']  = $v['amount']-$v['shipping_originask']; //付款金额减去运费 美元
                        $arr_order_list['goods_amount']  = $arr_order_list['goods_originask']*$arr_order_list['moneyrate'];//人民币


                        $arr_order_list['shipping_originask']  = $v['shipping_originask']; //原始快递费
                        $arr_order_list['shipping_fee']  = $v['shipping_fee']; //物流费 人民币
                        if($v['pay_fee']){
                            $arr_order_list['pay_fee']  = $arr_order_list['goods_amount']*0.015; //支付费用
                            //$arr_order_list['pay_fee']  = $v['pay_fee']; //支付费用
                        }
                        if($v['platform_fee']){
                            $arr_order_list['platform_fee']  = $arr_order_list['goods_amount']*0.1; //平台费用
                            //$arr_order_list['platform_fee']  = $v['platform_fee']; //平台费用
                        }

                        $arr_order_list['add_time'] = time();
                        if($v['orderweight']){
                            $arr_order_list['orderweight']  = $v['orderweight'];
                        }
                        $arr_order_list['saleschannel']  = 'Aliexpress';
                        $arr_order_list['order_status']  = 2; //已支付
                        //物流相关信息
                       
                        if($v['postageservice']){
                            $arr_order_list['postageservice']  = $v['postageservice']; //自选物流
                        }
                        //留言
                        if($v['remark']){
                            $arr_order_list['platform_message']  = $v['remark']; //备注
                        }

						$this->db->trans_begin();	//事务开始

                        $this->db->insert('db_order_list',$arr_order_list);
                        $insert_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
                        //更新日志记录
						$imgdata="";
                        $imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
                        $imgdata["updatetime"] = date("Y-m-d H:i:s");
                        $imgdata["createUid"] = 0;
                        $imgdata["types"] = 3;
                        $imgdata["content"] = '速卖通接口自动新增订单,交易ID='.$v['orderId'];
                        $imgdata["createUser"] ='auto';
                        $this->db->insert('db_goods_log', $imgdata);
                        $sql_ordersell = "SELECT * FROM db_aliexpress_ordertmpsell WHERE orderId = '{$v['orderId']}' ";
                        $rs_ordersell = $this->db->query($sql_ordersell)->result_array();
                        //var_dump($sql_ordersell);exit;
                        $flag = 0;
                        foreach($rs_ordersell as $key=>$value){
                            if($value['skuCode']){
                                $sql_s = "SELECT * FROM db_goods WHERE goods_sku = '".$value['skuCode']."' or cognatelist like '%,".$value['skuCode'].",%' ";
                                $rs_s = $this->db->query($sql_s)->row_array();
                                if(count($rs_s)>0){
                                    $goods_id = $rs_s['goods_id'];
                                }else{
                                    $flag = 1;
                                    $goods_id = 0;
                                }
                            }else{
                                $flag = 1;
                                $goods_id = 0;
                            }

                            $arr_order_sell['order_id'] = $insert_id;
                            $arr_order_sell['goods_id'] = $goods_id;
                            if($rs_s['goods_name']){
                                $arr_order_sell['goods_name'] = $rs_s['goods_name'];
                            }else{
                                $arr_order_sell['goods_name'] = $value['productName'];
                            }
                            $arr_order_sell['goods_sn'] = $value['skuCode'];
                            $arr_order_sell['goods_number'] = $value['productCount']; //商品数量
                            $arr_order_sell['originsellprice'] = $value['originsellprice'];
                            if($value['costprice']){
                                $arr_order_sell['costprice'] = $value['costprice'];
                            }
                            if($value['originsku']){
                                $arr_order_sell['originsku'] = $value['originsku'];//原始sku
                            }

                            $arr_order_sell['goods_price'] = $value['goods_price'];
                            $arr_order_sell['goods_amount'] = $value['goods_amount'];
                            $arr_order_sell['goods_attr'] = $value['productStandard'];//商品属性
                            $arr_order_sell['goods_weight'] = $value['grossWeight']?$value['grossWeight']:400;//毛重
                            if($value['productSnapUrl']){
                                $arr_order_sell['product_link'] = $value['productSnapUrl'];//毛重
                            }
							$arr_order_sell["productId"]=$value["productId"];
                            if($value['message']){
                                $arr_order_sell['sale_remark'] = $value['message'];//留言
                            }
                            $this->db->insert('db_order_sell',$arr_order_sell);
                            $insert_sell_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
                            
                           
                        }
                        if($flag){
                            $this->db->where('order_id',$insert_id);
                            $data['order_status'] = 7;
                            $this->db->update('db_order_list',$data);
                        }
                        //更新flag状态
                        $this->db->where('id',$v['id']);
                        $d['flag'] = 1;
                        $this->db->update('db_aliexpress_ordertmp',$d);
                        //var_dump($this->db->last_query());exit;
                        //若执行成功，则提交
                        
						if ($this->db->trans_status() === FALSE)
						{
							$this->db->trans_rollback();
						}
						else
						{
							$this->db->trans_commit();
						}
                   

                }

            }


    }
    /**
     * 获取订单并插入数据库表
     * @param $appKey 店铺分配的唯一appkey
     * @param $appScret 密钥
     * @param $access_token 访问令牌
     */
    private function getOrderList($appKey,$appScret,$access_token,$shopid,$shopname,$shop_oper){
        //获取上一次回去的最后一条订单日期数据
        /**
        $sql = "SELECT * FROM db_aliexpress_ordertmp ORDER BY gmtCreate DESC ";
        $rs = $this->db->query($sql)->row_array();
        if(count($rs)>0){
             $createDateStart = date("m/d/Y H:i:s",strtotime($rs['gmtCreate']));
             $createDateEnd = date("m/d/Y")." 23:59:59";
         }else{
            $createDateStart = "06/01/2017 00:00:00";
            $createDateEnd = "06/08/2017 23:59:59";
         }**/
        $date = date("m/d/Y H:i:s",strtotime('-28 days'));
        $now_date = date("m/d/Y H:i:s");
        $createDateStart = $date;
        $createDateEnd =  $now_date;
        //获取签名
        $api_relative_path = 'param2/1/aliexpress.open/api.findOrderListQuery' . '/' . $appKey;
        $arr_param = array('page' =>1, 'pageSize' =>50, 'createDateStart' => $createDateStart, 'createDateEnd' => $createDateEnd, 'access_token' => $access_token);
        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
        //获取api签名结束
        //根据签名获取订单数据
        $request_url = $this->urlApi . "api.findOrderListQuery/" .$appKey;
        $data = 'page=1&pageSize=50&createDateStart='.$createDateStart.'&createDateEnd='.$createDateEnd.'&access_token=' .$access_token . '&_aop_signature=' . $sign;
        $result = $this->sendCurlPostRequest($request_url, $data);
        //var_dump($result);exit;
        if(isset($result['error_code'])&&$result['error_code']==401){
            echo "Request need user authorized";
            echo "<br/>";
        }
        $result_count = $result['totalItem'];
        //循环插入数据库，并循环获取剩余数据
            if (count($result['orderList'])>0) {
                foreach ($result['orderList'] as $key => $value) {
                    if(false !==stripos($value['orderId'], "e")){
                        $value['orderId'] = number_format($value['orderId'],0,'','');
                    }
                    $sql = "SELECT * FROM db_aliexpress_ordertmp WHERE orderId = '{$value['orderId']}' ";
                    $rs = $this->db->query($sql)->row_array();
                    if($rs){
                        //如果已存在该状态，直接执行下个循环
                        if($rs['orderStatus']=="WAIT_SELLER_SEND_GOODS"){
                            //客户取消订单
                            if($value['orderStatus']=="IN_CANCEL"){
                                $sql_orderlist = "SELECT * FROM db_order_list WHERE tradeid = '{$value['orderId']}' ";
                                $rs_orderlist  = $this->db->query($sql_orderlist)->row_array();
                                if($rs_orderlist){
                                    //已支付或已配货状态
                                    if($rs_orderlist['order_status']==2||$rs_orderlist['order_status']==3){
                                        //禁止发货
                                        $this->db->update('db_order_list',array('is_nodelivery'=>1)," order_id=".$rs_orderlist['order_id']);
                                        //临时表也更新一下
                                        $this->db->update('db_aliexpress_ordertmp',array('orderStatus'=>'IN_CANCEL')," id=".$rs['id']);
                                        //更新日志记录
                                        $orderlog="";
                                        $orderlog["goods_id"] = $rs_orderlist['order_id'];	//订单ID db_order_list
                                        $orderlog["updatetime"] = date("Y-m-d H:i:s");
                                        $orderlog["createUid"] = 0;
                                        $orderlog["types"] = 3;
                                        $orderlog["content"] = '禁止发货，客户取消订单,交易ID='.$rs_orderlist['tradeid'];
                                        $orderlog["createUser"] ='auto';
                                        $this->db->insert('db_goods_log', $orderlog);
                                    }
                                }
                            }
                            continue;
                        }else{

                            //更db_aliexpress_ordertmp
                            if($value['orderStatus']=="WAIT_SELLER_SEND_GOODS"){
                                //删除临时数据，下文重新执行
                                $this->db->delete('db_aliexpress_ordertmp', array('orderId' =>$rs['orderId']));
                                $this->db->delete('db_aliexpress_ordertmpsell', array('orderId' =>$rs['orderId']));
                                //$this->db->where('id',$rs['id']);
                                //$this->db->update('db_aliexpress_ordertmp',array('orderStatus'=>'WAIT_SELLER_SEND_GOODS'));
                            }else{
                                continue;
                            }

                        }
                    }
                        $this->doExecuteInsert($appKey,$appScret,$access_token,$shopid,$shopname,$shop_oper,$value);
                }
                //var_dump($result_count);exit;
                //剩余页数 每页获取50条数据
                if ($result_count > 50) {
                    $len = (int) ceil($result_count / 50);
                    //从第二页开始在获取相关数据,第一页数据已插入相关信息
                    for ($i = 2; $i <= $len; $i++) {
                        //拼接api签名相关参数 查询订单列表相关信息
                        $api_relative_path = 'param2/1/aliexpress.open/api.findOrderListQuery' . '/' .$appKey;
                        $arr_param = array('page' => $i, 'pageSize' => 50, 'createDateStart' => $createDateStart, 'createDateEnd' => $createDateEnd, 'access_token' =>$access_token);
                        //$arr_param = array('page'=>1,'pageSize'=>20,'access_token'=>$v['access_token']);
                        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
                        //获取api签名结束
                        //需要根据返回的totalitem判断需要查询的次数，以及时间综合查询
                        $request_url = $this->urlApi . "api.findOrderListQuery/" .$appKey;
                        //$request_url = "http://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/api.getProductGroupList";
                        $data = 'page=' . $i . '&pageSize=50&createDateStart='.$createDateStart.'&createDateEnd='.$createDateEnd.'&access_token=' .$access_token. '&_aop_signature=' . $sign;
                        $result = $this->sendCurlPostRequest($request_url, $data);
                        //循环插入数据库，并循环获取剩余数据
                        if (!empty($result['orderList'])) {
                            foreach ($result['orderList'] as $key => $value) {
                                if(false !==stripos($value['orderId'], "e")){
                                    $value['orderId'] = number_format($value['orderId'],0,'','');
                                }
                                $sql = "SELECT * FROM db_aliexpress_ordertmp WHERE orderId = '{$value['orderId']}' ";
                                $rs = $this->db->query($sql)->row_array();
                                if($rs){
                                    //如果已存在该状态，直接执行下个循环
                                    if($rs['orderStatus']=="WAIT_SELLER_SEND_GOODS"){
                                        //客户取消订单
                                        if($value['orderStatus']=="IN_CANCEL"){
                                            $sql_orderlist = "SELECT * FROM db_order_list WHERE tradeid = '{$value['orderId']}' ";
                                            $rs_orderlist  = $this->db->query($sql_orderlist)->row_array();
                                            if($rs_orderlist){
                                                //已支付或已配货状态
                                                if($rs_orderlist['order_status']==2||$rs_orderlist['order_status']==3){
                                                    //禁止发货
                                                    $this->db->update('db_order_list',array('is_nodelivery'=>1)," order_id=".$rs_orderlist['order_id']);
                                                    //临时表也更新一下
                                                    $this->db->update('db_aliexpress_ordertmp',array('orderStatus'=>'IN_CANCEL')," id=".$rs['id']);
                                                    //更新日志记录
                                                    $orderlog="";
                                                    $orderlog["goods_id"] = $rs_orderlist['order_id'];	//订单ID db_order_list
                                                    $orderlog["updatetime"] = date("Y-m-d H:i:s");
                                                    $orderlog["createUid"] = 0;
                                                    $orderlog["types"] = 3;
                                                    $orderlog["content"] = '禁止发货，客户取消订单,交易ID='.$rs_orderlist['tradeid'];
                                                    $orderlog["createUser"] ='auto';
                                                    $this->db->insert('db_goods_log', $orderlog);
                                                }
                                            }
                                        }
                                        continue;
                                    }else{
                                        //更db_aliexpress_ordertmp
                                        if($value['orderStatus']=="WAIT_SELLER_SEND_GOODS"){
                                            //删除临时数据，下文重新执行
                                            $this->db->delete('db_aliexpress_ordertmp', array('orderId' =>$rs['orderId']));
                                            $this->db->delete('db_aliexpress_ordertmpsell', array('orderId' =>$rs['orderId']));

                                            //$this->db->where('id',$rs['id']);
                                            //$this->db->update('db_aliexpress_ordertmp',array('orderStatus'=>'WAIT_SELLER_SEND_GOODS'));
                                        }else{
                                            continue;
                                        }

                                    }
                                }
                                $this->doExecuteInsert($appKey,$appScret,$access_token,$shopid,$shopname,$shop_oper,$value);
                            }
                        }

                    }

                }

            }

    }
    //执行循环临时表操作 temp
    //@param $value  array 为订单数据组
    private function doExecuteInsert($appKey,$appScret,$access_token,$shopid,$shopname,$shop_oper,$value){
        //获取国家相关中文名
        $arr_country = array();
        $sql_country = "SELECT countryid,countrynameen,countrynamecn FROM d_country ";
        $rs_country = $this->db->query($sql_country)->result_array();
        foreach($rs_country as $k=>$v){
            $arr_country[$v['countryid']] = $v['countrynamecn'];  // 这个对应英文名
            $arr_country[$v['countrynamecn']] = $v['countrynameen']; // 英文名对应中文名
        }
        //获取相关货币跟人民币汇率列表
        $arr_rate = array();
        $sql_rate = "SELECT name,rate FROM d_moneyrate ";
        $rs_rate = $this->db->query($sql_rate)->result_array();
        foreach($rs_rate as $ka=>$va){
            $arr_rate[$va['name']] = $va['rate'];
        }
       // var_dump($value);exit;
        $this->db->trans_begin();
        try{
            $arr_ins['cent'] = $value['payAmount']['cent']; //付款金额 分
            $arr_ins['amount'] = $value['payAmount']['amount']; //付款金额
            $arr_ins['currencyCode'] = $value['payAmount']['currencyCode']; //当前货币
           // $arr_ins['loanAmount'] = serialize($value['loanAmount']);//放款金额
            //订单创建时间  更正为北京时间
            //$arr_ins['gmtCreate'] = $value['gmtCreate'];
            $gmt_datetime = substr($value['gmtCreate'],0,14);
            $tmp_datetime = substr($gmt_datetime,0,4)."-".substr($gmt_datetime,4,2)."-".substr($gmt_datetime,6,2)." ".substr($gmt_datetime,8,2).":".substr($gmt_datetime,10,2).":".substr($gmt_datetime,12,2);
            $arr_ins['gmtCreate'] = $tmp_datetime;
            $tmp_datetime = strtotime($tmp_datetime)+8*60*60;
            $bj_datetime  = date("Y-m-d H:i:s",$tmp_datetime);
            $arr_ins['gmtBjdate'] = $bj_datetime;
            if(false !==stripos($value['orderId'], "e")){
                $value['orderId'] = number_format($value['orderId'],0,'','');
            }
            if(isset($value['paymentType'])){
                $arr_ins['paymentType'] = $value['paymentType'];//支付类型
            }
            $arr_ins['orderStatus'] = $value['orderStatus'];//订单状态
            if(isset($value['leftSendGoodHour'])){
                $arr_ins['leftSendGoodHour'] = $value['leftSendGoodHour'];//剩余发货时间（小时） 备注：不是每个订单都有
            }
            $arr_ins['buyerSignerFullname'] = $value['buyerSignerFullname'];//买家全名
            if(isset($value['gmtPayTime'])){
                $gmt_datetime = substr($value['gmtPayTime'],0,14);
                $tmp_datetime = substr($gmt_datetime,0,4)."-".substr($gmt_datetime,4,2)."-".substr($gmt_datetime,6,2)." ".substr($gmt_datetime,8,2).":".substr($gmt_datetime,10,2).":".substr($gmt_datetime,12,2);
                $arr_ins['gmtPayTime'] = $tmp_datetime;
                //$arr_ins['gmtPayTime'] = $value['gmtPayTime'];//支付时间（和订单详情中gmtPaysuccess字段意义相同。)
            }
            $arr_ins['timeoutLeftTime'] = $value['timeoutLeftTime'];//超时剩余时间
            $arr_ins['frozenStatus'] = $value['frozenStatus'];//冻结状态
            $arr_ins['issueStatus'] = $value['issueStatus'];//纠纷状态
            if(isset($value['leftSendGoodMin'])){
                $arr_ins['leftSendGoodMin'] = $value['leftSendGoodMin'];//剩余发货时间（分钟) 备注：不是每个订单都有
            }
            $arr_ins['fundStatus'] = $value['fundStatus'];//资金状态
            $arr_ins['buyerLoginId'] = $value['buyerLoginId'];//买家登录ID
            $arr_ins['sellerSignerFullname'] = $value['sellerSignerFullname'];//卖家全名
           // if(isset($value['escrowFee'])){
            //    $arr_ins['escrowFee'] = serialize($value['escrowFee']);//手续费 该项为数组后处理 序列化后存入数据库
           // }
            $arr_ins['bizType'] = $value['bizType'];//订单类型
            $arr_ins['hasRequestLoan'] = $value['hasRequestLoan'];//是否已请求放款
            if(isset($value['leftSendGoodDay'])){
                $arr_ins['leftSendGoodDay'] = $value['leftSendGoodDay'];//剩余发货时间（天） 备注：不是每个订单都有
            }
            $arr_ins['orderId'] = $value['orderId'];//订单ID

            //拼接api签名   获取订单收货信息
            /**
            $api_rela_path = 'param2/1/aliexpress.open/api.findOrderReceiptInfo' . '/' . $appKey;
            $ary_param = array('orderId'=>$value['orderId'], 'access_token' => $access_token);
            $receiner_sign = $this->getApiSign($api_rela_path, $appKey, $appScret, $ary_param);
            //获取api签名结束
            //获取收货信息
            $req_url = $this->urlApi . "api.findOrderReceiptInfo/" .$appKey;
            $url_data = 'orderId='.$value['orderId'].'&access_token=' .$access_token . '&_aop_signature=' . $receiner_sign;
            $res_s = $this->sendCurlPostRequest($req_url, $url_data);
             * */

            //拼接api签名   获取订单详情信息，里面包含地址等信息 订单 物流等等
            $api_rela_path = 'param2/1/aliexpress.open/api.findOrderById' . '/' . $appKey;
            $ary_param = array('orderId'=>$value['orderId'], 'access_token' => $access_token);
            $receiner_sign = $this->getApiSign($api_rela_path, $appKey, $appScret, $ary_param);
            //获取api签名结束
            //获取收货信息
            $req_url = $this->urlApi . "api.findOrderById/" .$appKey;
            $url_data = 'orderId='.$value['orderId'].'&access_token=' .$access_token . '&_aop_signature=' . $receiner_sign;
            $res = $this->sendCurlPostRequest($req_url, $url_data);
            if(isset($res['receiptAddress']['phoneNumber'])&&$res['receiptAddress']['phoneNumber']){
                $phone = "";
                if($res['receiptAddress']['phoneCountry']){
                      $phone =  $res['receiptAddress']['phoneCountry'];
                }
                if($res['receiptAddress']['phoneArea']){
                    if($phone){
                        $phone = $phone."-".$res['receiptAddress']['phoneArea'];
                    }else{
                        $phone = $res['receiptAddress']['phoneArea'];
                    }

                }
                $arr_ins['phoneNumber'] = $phone."-".$res['receiptAddress']['phoneNumber'];
             //$arr_ins['phoneNumber'] = $res['receiptAddress']['phoneCountry']."-".$res['receiptAddress']['phoneArea']."-".$res['receiptAddress']['phoneNumber'];//电话
            }
            if(isset($res['receiptAddress']['province'])){
                $arr_ins['province'] = addslashes($res['receiptAddress']['province']);//订单ID
            }
            if(isset($res['receiptAddress']['phoneArea'])){
                $arr_ins['phoneArea'] = $res['receiptAddress']['phoneArea'];//订单ID
            }
            if(isset($res['receiptAddress']['country'])){
                $arr_ins['country_code'] = $res['receiptAddress']['country'];//国家简称
                if($res['receiptAddress']['country']=="SRB"){
                    $res['receiptAddress']['country']="RS"; //二字码
                }

                $arr_ins['country'] =strtolower($arr_country[$res['receiptAddress']['country']]);//国家英文
                $arr_ins['country_cn'] = $arr_country[$arr_country[$res['receiptAddress']['country']]];//国家中文
            }
            if(isset($res['receiptAddress']['contactPerson'])){
                $arr_ins['contactPerson'] =addslashes( $res['receiptAddress']['contactPerson']);//订单ID
            }
            if(isset($res['receiptAddress']['mobileNo'])){
                if(isset($res['receiptAddress']['phoneCountry'])){
                    $arr_ins['phoneCountry'] = $res['receiptAddress']['phoneCountry'];//订单ID
                    //$arr_ins['mobileNo'] = trim($res['receiptAddress']['phoneCountry'],"+").$res['receiptAddress']['mobileNo'];//订单ID
                    $arr_ins['mobileNo'] = $res['receiptAddress']['mobileNo'];//订单ID
                }else{
                    $arr_ins['mobileNo'] = $res['receiptAddress']['mobileNo'];//订单ID
                }
            }
            if(isset($res['receiptAddress']['city'])){
                $arr_ins['city'] = addslashes($res['receiptAddress']['city']);//订单ID
            }
            if(isset($res['receiptAddress']['detailAddress'])){
                $arr_ins['detailAddress'] = addslashes($res['receiptAddress']['detailAddress']);//订单ID
            }
            if(isset($res['receiptAddress']['address'])){
                $arr_ins['address'] = addslashes($res['receiptAddress']['address']);//订单ID
            }
            if(isset($res['receiptAddress']['address2'])&&$res['receiptAddress']['address2']) {
                $arr_ins['address2'] = addslashes($res['receiptAddress']['detailAddress']." ,".$res['receiptAddress']['address2']);//订单ID
            }else{
                $arr_ins['address2'] = addslashes($res['receiptAddress']['detailAddress']);
            }
            if(isset($res['receiptAddress']['zip'])){
                $arr_ins['zip'] = $res['receiptAddress']['zip'];//订单ID
            }
            //物流信息更新
            if(isset($res['logisticInfoList']['shipOrderId'])){
                $arr_ins['shipping_id'] = $res['logisticInfoList']['shipOrderId'];//订单ID
            }
            if(isset($res['logisticInfoList']['logisticsTypeCode'])){
                $arr_ins['shipping_name'] = $res['logisticInfoList']['logisticsTypeCode'];//订单ID
            }
            if(isset($res['logisticInfoList']['gmtSend'])){
                $arr_ins['shipping_time'] = $res['logisticInfoList']['gmtSend'];//订单ID
            }
            $arr_ins['shopid']  = $shopid; //店铺id
            $arr_ins['shopname']  = $shopname; //店铺名称
            $arr_ins['shopoper']  = $shop_oper;//店铺负责人
            //获取留言数据 orderMsgList
            if(isset($res['orderMsgList']['content'])){
                $arr_ins['remark']  = $res['orderMsgList']['content'];//订单留言
            }
           // var_dump($arr_ins);exit;
            //相关费用计算
            if(isset($res['escrowFee']['amount'])){
                $arr_ins['escrowFee']  = $res['escrowFee']['amount']*$arr_rate[$res['escrowFee']['currencyCode']]; //手续费用 人民币
            }
            if(isset($res['loanInfo']['amount'])){
                $arr_ins['loanInfo']  =  $res['loanInfo']['amount']*$arr_rate[$res['loanInfo']['currencyCode']]; //放款费用 人民币
            }
            $arr_ins['goods_originask']  = $res['orderAmount']['amount']; //订单金额
            //商品总金额不是该计算方法
            //$arr_ins['goods_amount']  = $res['orderAmount']['amount']*$arr_rate[$res['orderAmount']['currencyCode']]; //订单金额 人民币
              //使用商品进行计算
            //$arr_ins['goods_amount'] = $res['childOrderExtInfoList']['unitPrice']['amount']*$arr_rate[$res['childOrderExtInfoList']['unitPrice']['currencyCode']]*$res['childOrderExtInfoList']['quantity'];
            $goods_count = 0;
            //该数据获得有问题，下文计算
            //foreach($res['childOrderExtInfoList'] as $ky=>$ve){
             //   if($ve['quantity']){
            //        $goods_count+= $ve['unitPrice']['amount']*$arr_rate[$ve['unitPrice']['currencyCode']]*$ve['quantity'];
            //    }else{
            //        $goods_count+= $ve['unitPrice']['amount']*$arr_rate[$ve['unitPrice']['currencyCode']];
            //    }
          //  }
            $arr_ins['goods_amount'] = $goods_count;
            $arr_ins['shipping_originask']  = $res['logisticsAmount']['amount']; //原始快递费
            if($res['logisticsAmount']['amount']){
                $arr_ins['shipping_originask']  = $res['logisticsAmount']['amount']; //原始快递费
            }else{
                $arr_ins['shipping_originask']  = 0; //原始快递费
            }
            $arr_ins['shipping_fee']  = $res['logisticsAmount']['amount']*$arr_rate[$res['logisticsAmount']['currencyCode']]; //物流费 人民币

            //商品金额  为订单金额减去原始快递费
            $arr_ins['goods_originask']  = $res['orderAmount']['amount']-$arr_ins['shipping_originask']; //订单金额

            //插入订单临时数据表
            $this->db->insert('db_aliexpress_ordertmp',$arr_ins);
            $insert_id = $this->db->insert_id();
            //var_dump($value['productList']);exit;//商品列表 该项为数组，需要重新处理
            $weight = 0; //合计总重量
            if(count($value['productList'])>0){
                foreach($value['productList'] as $kk=>$vv){
                    //var_dump($vv);exit;
                    if(isset($vv['logisticsServiceName'])){
                        $arr_goods['logisticsServiceName'] = $vv['logisticsServiceName'];
                    }
                    $arr_goods['logisticsAmount_cent'] = $vv['logisticsAmount']['cent'];
                    $arr_goods['logisticsAmount_amount'] = $vv['logisticsAmount']['amount'];
                    $arr_goods['logisticsAmount_currencyCode'] = $vv['logisticsAmount']['currencyCode'];
                    if(isset($vv['childId'])){
                        $arr_goods['childId'] = $vv['childId'];
                    }
                    if(isset($vv['goodsPrepareTime'])){
                        $arr_goods['goodsPrepareTime'] = $vv['goodsPrepareTime'];
                    }
                    /**
                    if($value['orderId']=='86600431333902'){
                       echo "<xmp>";
                        print_r($res);
                        echo "<br/>";
                            print_r($vv);
                        echo "<br/>";
                        print_r($value);exit;
                    }**/
                    if(isset($res['childOrderExtInfoList'][$kk]['sku'])){
                        $arr_child_sku = (array) json_decode($res['childOrderExtInfoList'][$kk]['sku']);
                        $msg = "";
                        foreach($arr_child_sku['sku'] as $sk=>$sv){
                            if($sv->selfDefineValue){
                                $msg.=$sv->pName.":".$sv->selfDefineValue;
                            }else{
                                $msg.=$sv->pName.":".$sv->pValue." ";
                            }
                        }
                        $arr_goods['message'] = $msg;
                    }

                    if(isset($vv['memo'])){
                        $arr_goods['memo'] = $vv['memo'];
                    }
                    if(isset($vv['sellerSignerFirstName'])){
                        $arr_goods['sellerFirstName'] = $vv['sellerSignerFirstName'];
                    }
                    if(isset($vv['sonOrderStatus'])){
                        $arr_goods['sonOrderStatus'] = $vv['sonOrderStatus'];
                    }
                    if(isset($vv['totalProductAmount'])){
                        $arr_goods['totalProductAmount_cent'] = $vv['totalProductAmount']['cent']; //数组
                        $arr_goods['totalProductAmount_amount'] = $vv['totalProductAmount']['amount']; //数组
                        $arr_goods['totalProductAmount_currencyCode'] = $vv['totalProductAmount']['currencyCode']; //数组
                    }
                    if(isset($vv['freightCommitDay'])){
                        $arr_goods['freightCommitDay'] = $vv['freightCommitDay'];
                    }
                    if(isset($vv['canSubmitIssue'])){
                        $arr_goods['canSubmitIssue'] = $vv['canSubmitIssue'];
                    }
                    if(isset($vv['productSnapUrl'])){
                        $arr_goods['productSnapUrl'] = $vv['productSnapUrl'];
                    }
                    if(isset($vv['productUnit'])){
                        $arr_goods['productUnit'] = $vv['productUnit'];
                    }
                    if(isset($vv['moneyBack3x'])){
                        $arr_goods['moneyBack3x'] = $vv['moneyBack3x'];
                    }
                    if(isset($vv['skuCode'])){
                        $arr_goods['skuCode'] = $vv['skuCode'];
                    }else{
                        if(isset($vv['productId'])){
                            //84787687520817
                            $arr_goods['skuCode'] = $vv['productId'];
                        }
                    }
                    if(isset($vv['sendGoodsTime'])){
                       //$arr_goods['sendGoodsTime'] = $vv['sendGoodsTime'];
                        $gmt_datetime = substr($vv['sendGoodsTime'],0,14);
                        $tmp_datetime = substr($gmt_datetime,0,4)."-".substr($gmt_datetime,4,2)."-".substr($gmt_datetime,6,2)." ".substr($gmt_datetime,8,2).":".substr($gmt_datetime,10,2).":".substr($gmt_datetime,12,2);
                        $arr_goods['sendGoodsTime'] = $tmp_datetime;

                    }
                    $arr_goods['productId'] = $vv['productId'];
                    $arr_goods['issueStatus'] = $vv['issueStatus'];
                    $arr_goods['logisticsType'] = $vv['logisticsType'];
                    $arr_goods['productCount'] = $vv['productCount'];
                    $arr_goods['deliveryTime'] = $vv['deliveryTime'];
                    $arr_goods['productUnitPrice_cent'] = $vv['productUnitPrice']['cent']; //数组
                    $arr_goods['productUnitPrice_amount'] = $vv['productUnitPrice']['amount']; //数组
                    $arr_goods['productUnitPrice_currencyCode'] = $vv['productUnitPrice']['currencyCode']; //数组
                    $arr_goods['sellerLastName'] = $vv['sellerSignerLastName'];
                    $arr_goods['productImgUrl'] = $vv['productImgUrl'];
                    $arr_goods['showStatus'] = $vv['showStatus'];
                    $arr_goods['productName'] = $vv['productName'];
                    if(false !==stripos($value['orderId'], "e")){
                        $vv['orderId'] = number_format($value['orderId'],0,'','');
                    }
                    $arr_goods['orderId'] = $value['orderId'];
                    //$arr_goods['orderId'] = $value['orderId'];
                    //api签名  调用商品id接口获取该商品的更多信息
                    $api_rela_path = 'param2/1/aliexpress.open/api.findAeProductById' . '/' . $appKey;
                    $ary_param = array('productId'=>$vv['productId'], 'access_token' => $access_token);
                    $receiner_sign = $this->getApiSign($api_rela_path, $appKey, $appScret, $ary_param);
                    //获取api签名结束
                    //调用商品id接口获取该商品的更多信息
                    $req_url = $this->urlApi . "api.findAeProductById/" .$appKey;
                    $url_data = 'productId='.$vv['productId'].'&access_token=' .$access_token . '&_aop_signature=' . $receiner_sign;
                    $rs_product = $this->sendCurlPostRequest($req_url, $url_data); //单个商品信息，数组格式
                    //var_dump($rs_product);exit;
                    //var_dump($vv['productStandard']);exit;
                    $arr_goods['productPrice'] = $rs_product['productPrice']; //商品销售价  数据库字段暂未设置
                    $arr_goods['grossWeight'] = $rs_product['grossWeight']; //产品毛重
                    $arr_goods['productStandard'] = isset($vv['productStandard'])?$vv['productStandard']:""; //商品属性
                    $arr_goods['originsellprice'] = $vv['productUnitPrice']['amount']; //需要核算的原始价格可能为美元
                    if($arr_goods['skuCode']){
                        $sql_search_goods = "SELECT * FROM db_goods WHERE goods_sku = '{$arr_goods['skuCode']}' or cognatelist like '%,".$arr_goods['skuCode'].",%'  ";
                        $rs_search_goods = $this->db->query($sql_search_goods)->row_array();
                    }
                    //print_r($sql_search_goods);exit;
                   // if($rs_search_goods){
                   //     $arr_goods['costprice'] = $rs_search_goods['g_costprice']; //成本价格 若没有从db_goods表找
                   // }else {
                   //     $arr_goods['costprice'] = 0; //成本价格 若没有从db_goods表找
                   // }
                    //上文价格重新计算date 2016/6/14
                    $costprice = 0;
                    $factorycode = $this->CI->amazondata->factorycode();
                    if(is_numeric($arr_goods['skuCode'])&&preg_match('|^\d{8}$|',$arr_goods['skuCode'])){
                        $goodscode = substr($arr_goods['skuCode'],0,2);
                        if(in_array($goodscode,$factorycode)){
                            $costprice = $rs_search_goods['g_costprice'];
                        }
                    }else{
						//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
						if(is_numeric($rs_search_goods["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rs_search_goods["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
						{
							$goodscodes  = substr($rs_search_goods["goods_parent_sku"],0,2);//取开头2位数
							if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rs_search_goods["bulkprice"];	//批量按关联价计算
							}
						}else{
							$costprice = $rs_search_goods["g_costprice"];
						}
                    }
                   
                    $arr_goods['costprice']=$costprice;

                    $arr_goods['goods_price'] = $arr_goods['originsellprice']*$arr_rate[$vv['productUnitPrice']['currencyCode']]; //商品原始价格 核算为人民币后的价格
                    $arr_goods['goods_amount'] = $vv['productCount']*$vv['productUnitPrice']['amount']*$arr_rate[$vv['productUnitPrice']['currencyCode']]; //商品销售总价 核算为人民币后的价格
                    $goods_count+= $arr_goods['goods_amount'];
                    if($rs_search_goods["goods_id"])
                    {
                        $goods_id = $rs_search_goods["goods_id"];
                        $arr_goods['goods_name'] = $rs_search_goods['goods_name'];
                        $arr_goods['originsku'] = $rs_search_goods['goods_parent_sku'];//原始sku
                        $sweight = $vv['productCount'] * $rs_search_goods["g_weight"];
                        $weight = $weight+$sweight;
                    }else{
                        $goods_id = 0 ;
                    }
                    //var_dump($rs_search_goods);exit;
                    $arr_goods['goods_id'] = $goods_id;
                    $this->db->insert('db_aliexpress_ordertmpsell',$arr_goods);
//                    if($arr_goods['orderId']=='84390414270287'){
//                            echo $this->db->last_query();exit;
//                    }
                    //var_dump($this->db->last_query());exit;
                    $logisticsServiceName = $vv['logisticsServiceName'];
                }
                if($weight){
					 $ary_data['orderweight'] = $weight;
				}
                   // $arr_ins['pay_fee']  = $arr_ins['goods_amount']*0.015; //支付费用
                   // $arr_ins['platform_fee']  = $arr_ins['goods_amount']*0.15; //平台费用
                    $ary_data['pay_fee'] = $goods_count*0.015;
                    $ary_data['platform_fee'] = $goods_count*0.1;
                    $ary_data['goods_amount'] = $goods_count;
                    $ary_data['shipping_name'] = $logisticsServiceName;
                    $this->db->where('id',$insert_id);
                    $this->db->update('db_aliexpress_ordertmp',$ary_data);
              
            }
            $this->db->trans_commit(); //若执行成功，则提交
        }catch (Exception $e){
            $this->db->trans_rollback();
            //echo $e->getMessage();
        }




    }

	/*******
	** 速卖通无忧物流交运
	** 1、先创建物流订单
	** 2、通过订单号隔2分钟获取国际物流单号
	** 3、通过国际物流单号获取面单信息
	** 说明连接：
	http://bbs.seller.aliexpress.com/bbs/read.php?spm=5261.7753646.1998612679.18.U0N4u4&tid=234971&page=1&toread=1#tpc
	****************/
	public function aliexpresswuliu()
	{
		$where  = "isexe = 0 AND orderType =9";
		$this->db->where($where);
		$total = $this->db->count_all_results('db_mabangorder');
		if($total==0)
		{
			echo "交运完成！";
			echo "<meta http-equiv=\"refresh\" content=\"1; url=/exportorder/ajaxbutton?op=aliexpresswuliuTwo \">";
			die;
		}
		$rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 0 AND orderType =9 ORDER BY id ASC");
		//获取店铺的配置信息
		$rsshop = $this->db->get_one("SELECT * FROM d_shop where name='".trim($rsdb["customertype"])."'");
		if($rsdb['isform']==1){
             $Morder = $this->db->get_one("SELECT * FROM db_mabangorder where orderID = '".$rsdb["orderID"]."'");   
			 $order["tel"] = $Morder["customertel1"];
			 $order["city"] = $Morder["customercity"];
			 $order["country"] = $Morder["customercountry"];
			 $order["country_code"] = $Morder["customerqq"];
			 $order["consignee"] = $Morder["customerid"];
			 $order["mobile"]   = $Morder["customertel2"];
			 $order["zipcode"]   = $Morder["customerzipcode"];
			 $order["province"]   = $Morder["customerprovince"];
			 $order["address"]   = $Morder["customeraddress"];
			 $order["tradeid"]  = $Morder["orderID"];
			 $MAliordersell = $this->db->get_one("SELECT * FROM db_mabangsell where orderId = '".$order["tradeid"]."'");
			 $Aliordersell["productId"] = $MAliordersell["productid"];

			
        }else{
			$order = $this->db->get_one("SELECT * FROM db_order_list where order_sn = '".$rsdb["orderID"]."'");
			
			$Aliordersell = $this->db->get_one("SELECT * FROM db_aliexpress_ordertmpsell where orderId = '".$order["tradeid"]."'");
			if($Aliordersell['productId']=='')
			{
				$newpsli = $this->db->get_one("SELECT * FROM db_order_sell where order_id = '".$order["order_id"]."' AND product_link !=''");
				$Aliordersell['productId'] = $newpsli['product_link'];
			}
		}


		if($order["country_code"] == '')
		{
			$rscountry = $this->db->get_one("select * from d_country where countrynamecn='".$order["country"]."'");
			$countryid = $rscountry['countryid'];
		}
		$order["tel"] = str_replace("+","",$order["tel"]);	//电话中有加号，去掉
		$wuyconfig = unserialize($rsdb["wuyconfig"]);
		$receiver = "";
		$sender="";
		$receiver["city"] = $order["city"];
		$receiver["country"] = $order["country_code"]?$order["country_code"]:$countryid;
		$receiver["mobile"] = $order["tel"];
		$receiver["memberType"] = 'receiver';
		$receiver["name"] = $order["consignee"];
		$receiver["phone"] = $order["mobile"]?$order["mobile"]:$order["tel"];
		$receiver["postcode"] = $order["zipcode"];
		$receiver["province"] = $order["province"];
		$receiver["streetAddress"] = $order["address"].$order["address2"];
		
		
		$appKey = $rsshop["appkey"];
		$appScret = $rsshop["appsecret"];
		$access_token = $rsshop["access_token"];
		

		//获取卖家地址信息
		$requeststr=array('sender','refund');
		$requeststr = json_encode($requeststr);
		$api_relative_path = 'param2/1/aliexpress.open/alibaba.ae.api.getLogisticsSellerAddresses' . '/' . $appKey;
        $arr_param = array('request'=>$requeststr,'access_token' => $access_token);
        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);

		$request_url = $this->urlApi . "alibaba.ae.api.getLogisticsSellerAddresses/" .$appKey;
		$data = 'request='.$requeststr.'&access_token=' .$access_token . '&_aop_signature=' . $sign;
		$result = $this->sendCurlPostRequest($request_url, $data);
	
		if($result){
			if($result['error_code'] ==401)
			{
				$postdata="";
				$postdata["isexe"] = 2;
				$postdata["exememo"] = "交运失败：".json_encode($result);
				$postdata["mailinstime"] =time();
				$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$rsdb["id"]));
			}
			$sender["addressId"] = $result["senderSellerAddressesList"][0]["addressId"];
			$refund["addressId"] = $result["refundSellerAddressesList"][0]["addressId"];
		}
		$addressDTOs["receiver"] = $receiver;	//收件地址
		$aliexpressData = unserialize($rsshop["aliexpressData"]);
		$sender["city"] = $aliexpressData["city"];
		$sender["country"] ='CN';
		$sender["mobile"] = $aliexpressData["tel"];
		$sender["memberType"] = 'sender';
		$sender["name"] = $aliexpressData["name"];
		$sender["postcode"] = $aliexpressData["postcode"];
		$sender["province"] = $aliexpressData["province"];
		$sender["streetAddress"] = $aliexpressData["address"];
		$addressDTOs["sender"] = $sender;	//发件人
		$addressDTOs["refund"] = $refund;	//退货地址
		$addressDTOs = json_encode($addressDTOs);
		
		$declareProductDTOs =array(); //产品信息
		$declareProductDTOs[0]["productId"] = $Aliordersell["productId"];
		$declareProductDTOs[0]["categoryCnDesc"] = '配件';
		$declareProductDTOs[0]["categoryEnDesc"] = 'costume accessory';
		$declareProductDTOs[0]["productNum"] = 1;
		$declareProductDTOs[0]["productDeclareAmount"] = 6.99;
		$declareProductDTOs[0]["productWeight"] = 0.4;
		$declareProductDTOs[0]["isContainsBattery"] = $wuyconfig['isbattery'];
		$declareProductDTOs[0]["isAneroidMarkup"] =0;


		
		$declareProductDTOs = json_encode($declareProductDTOs);

		
		//获取线上方案【warehouseCarrierService】
		/*
		$api_relative_path = 'param2/1/aliexpress.open/api.getOnlineLogisticsServiceListByOrderId' . '/' . $appKey;
        $arr_param = array('orderId'=>$order["tradeid"],'access_token' => $access_token);
        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);

		$request_url = $this->urlApi . "api.getOnlineLogisticsServiceListByOrderId/" .$appKey;
		$data = 'orderId='.$order["tradeid"].'&access_token=' .$access_token . '&_aop_signature=' . $sign;
		$result = $this->sendCurlPostRequest($request_url, $data);
		if($result){
			print_r($result);
			die;
		}
		die;
		*/

		//获取签名
        $api_relative_path = 'param2/1/aliexpress.open/api.createWarehouseOrder' . '/' . $appKey;
        $arr_param = array('tradeOrderId' =>$order["tradeid"], 'tradeOrderFrom' =>'ESCROW','warehouseCarrierService'=>$wuyconfig['Expressqudao'],'domesticLogisticsCompanyId'=>$wuyconfig['kd'],"domesticTrackingNo"=>$wuyconfig['kdnumber'],"declareProductDTOs"=>$declareProductDTOs,"addressDTOs"=>$addressDTOs,'undeliverableDecision'=>0,'access_token' => $access_token);

		
        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
	
		$request_url = $this->urlApi . "api.createWarehouseOrder/" .$appKey;
        $data = 'tradeOrderId='.$order["tradeid"].'&tradeOrderFrom=ESCROW&warehouseCarrierService='.$wuyconfig['Expressqudao'].'&domesticLogisticsCompanyId='.$wuyconfig['kd'].'&domesticTrackingNo='.$wuyconfig['kdnumber'].'&declareProductDTOs='.$declareProductDTOs.'&addressDTOs='.$addressDTOs.'&undeliverableDecision=0&access_token=' .$access_token . '&_aop_signature=' . $sign;
        $resultnew = $this->sendCurlPostRequest($request_url, $data);
		if($resultnew["success"])	//创建无误
		{
			$postdata="";
			$postdata["isexe"] = 3;
			$postdata["exememo"] = "等待获取运单号";
			$postdata["mailinstime"] =time();
			$postdata["wuyresultdata"] = serialize($resultnew);
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$rsdb["id"]));
			
		}else{
			$postdata="";
			$postdata["isexe"] = 2;
			$postdata["exememo"] = "交运失败<br>".json_encode($resultnew);
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$rsdb["id"]));
		}

		return $rsdb["orderID"].$postdata["exememo"];
		
	}

	function aliexpresswuliuTwo()
	{
		$where  = "isexe = 3 AND orderType =9";
		$this->db->where($where);
		$total = $this->db->count_all_results('db_mabangorder');
		if($total==0)
		{
			echo "交运完成！";
			echo "<meta http-equiv=\"refresh\" content=\"1; url=/deliverorder/aliexpressOrder \">";
			die;
		}

		$rsdb = $this->db->get_one("SELECT * FROM db_mabangorder WHERE isexe = 3 AND orderType =9 ORDER BY id ASC");
		//获取店铺的配置信息
		$rsshop = $this->db->get_one("SELECT * FROM d_shop where name='".trim($rsdb["customertype"])."'");
		
		if($rsdb['isform']==1){
           $Morder = $this->db->get_one("SELECT * FROM db_mabangorder where orderID = '".$rsdb["orderID"]."'");   
			$order["tradeid"] = $Morder["orderID"];
        }else{
			$order = $this->db->get_one("SELECT * FROM db_order_list where order_sn = '".$rsdb["orderID"]."'");
		}


		
		$appKey = $rsshop["appkey"];
		$appScret = $rsshop["appsecret"];
		$access_token = $rsshop["access_token"];
		//获取签名
        $api_relative_path = 'param2/1/aliexpress.open/api.getOnlineLogisticsInfo' . '/' . $appKey;
        $arr_param = array('orderId' =>$order["tradeid"],'access_token' => $access_token);
        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);

		$request_url = $this->urlApi . "api.getOnlineLogisticsInfo/" .$appKey;
        $data = 'orderId='.$order["tradeid"].'&access_token=' .$access_token . '&_aop_signature=' . $sign;
        $resultdata = $this->sendCurlPostRequest($request_url, $data);
		
	
		
		if($resultdata["success"])	//创建无误
		{
			//$nums = count($resultdata["result"]);
			//$kyes = $nums-1;
			$internationallogisticsId = $resultdata["result"][0]["internationallogisticsId"];//运单号,多次交运留最新的一个
			
			$updatedata = serialize($resultdata);
			$this->db->query($this->db->update_string('db_mabangorder', array("wuyresultdata"=>$updatedata), 'id=' .$rsdb["id"]));
			//获取签名
			$api_relative_path = 'param2/1/aliexpress.open/api.getPrintInfo' . '/' . $appKey;
			$arr_param = array('internationalLogisticsId' =>$internationallogisticsId,'access_token' => $access_token);
			$sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
			$request_url = $this->urlApi . "api.getPrintInfo/" .$appKey;
			$data = 'internationalLogisticsId='.$internationallogisticsId.'&access_token=' .$access_token . '&_aop_signature=' . $sign;
			$resultdatas = $this->sendCurlPostRequest($request_url, $data);
			if($resultdatas["StatusCode"]==200)
			{
				$postdata="";
				//保存图片到本地
				$dir = dirname(__FILE__) . "/../../uploads/wuyexpress/".date("Ymd");
				!is_dir($dir) && @mkdir($dir, 0755, true);
				$Path = $dir. "/".$internationallogisticsId."-".time().".pdf";
				$content=$resultdatas["body"];
				if(file_put_contents($Path, base64_decode($content)))
				{
					$pathst = str_replace(dirname(__FILE__) . "/../../", '', $Path);
					$postdata["printUrl"] = $pathst;
					//下载好的pdf转成png
					$rsdbts = $this->CI->fun->pdf2png($Path);
					$postdata["print_img"] = $rsdbts[0];
				}

				
				$postdata["isexe"] = 1;
				$postdata["exememo"] = "交运成功";
				$postdata["mailNo"] = $internationallogisticsId;
				$postdata["originCode"] = 0;
				$postdata["destCode"] = 0;
				$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$rsdb["id"]));
				$update_order = "";
				$update_order["shipping_number"] = $internationallogisticsId;	//运单号
				$update_order["shipping_time"] = time();				//交运时间
				$update_order["shipping_name"] = "无忧物流";
				$shipping =$this->db->get_one("select * from db_order_express where name='无忧物流'");
				$update_order["shipping_id"] = $shipping["id"]?$shipping["id"]:22;
				$update_order["shipping_expectfee"] = 0;
				if($rsdb['isform']==1){
				
				}else{
					$this->db->query($this->db->update_string('db_order_list', $update_order, 'order_id=' .$order["order_id"]));
				}

				//更新日志表db_goods_log
					$imgdata="";
                    $imgdata["goods_id"] = $order['order_id'];	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = 0;
                    $imgdata["types"] = 3;
                    $imgdata["content"] = '无忧交运完成,交易ID='.$order['tradeid'].",运单号=".$internationallogisticsId;
                    $imgdata["createUser"] ='auto';
                    $this->db->insert('db_goods_log', $imgdata);
			}
			
		}else{
			$postdata="";
			$postdata["isexe"] = 2;
			$postdata["exememo"] = "交运失败<br>".json_decode($resultdata);
			$postdata["mailinstime"] =time();
			$this->db->query($this->db->update_string('db_mabangorder', $postdata, 'id=' .$rsdb["id"]));
		}
		return $rsdb["orderID"].$postdata["exememo"];
	}
	/******************************
	** 速卖通无忧物流交运结束
	****************************/

    //获取api数字签名
    protected function getApiSign($api_relative_path,$appKey,$appSecret,$arr_param){
        $url = 'http://gw.api.alibaba.com/openapi';//1688开放平台使用gw.open.1688.com域名
        $apiInfo = $api_relative_path;//此处请用具体api进行替换
        //配置参数，请用apiInfo对应的api参数进行替换
        $code_arr = $arr_param;
        $aliParams = array();
        foreach ($code_arr as $key => $val) {
            $aliParams[] = $key . $val;
        }
        sort($aliParams);
        $sign_str = join('',$aliParams);
        $sign_str = $apiInfo.$sign_str;
        $code_sign = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
        return $code_sign;
    }
    /*
    * 通过refreshToken换取accessToken
    */
    protected function getAccessToken($refreshtoken,$appkey,$appsecret)
    {
        $getTokenUrl = 'https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/getToken/'.$appkey;
        //此处不需要签名  注：此接口必须使用POST方法提交；必须使用https
        $data = 'grant_type=refresh_token&client_id='.$appkey.'&client_secret='.$appsecret.'&refresh_token='.$refreshtoken;
        $result = $this->sendCurlPostRequest($getTokenUrl,$data);
        return $result;
    }
    /*
    * 半年期限，剩余30天之内可以使用postponeToken接口换取新的refresh_token
     * 若调用该接口则之前使用refresh_token失效，新获取的refresh_token生效
    */
    protected function getRefreshToken($refreshtoken,$access_token,$appkey,$appsecret)
    {
        $getTokenUrl = 'https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/postponeToken/'.$appkey;
        //此处不需要签名  注：此接口可以使用Get或POST方法提交；必须使用https
        $data = 'client_id='.$appkey.'&client_secret='.$appsecret.'&refresh_token='.$refreshtoken.'&access_token='.$access_token;
        $result = $this->sendCurlPostRequest($getTokenUrl,$data);
        //返回数组类型的数据格式
        // {"aliId":"8888888888","resource_owner":"xxx","memberId":"xxxxxxx","expires_in":"36000","refresh_token":"479f9564-1049-456e-ab62-29d3e82277d9","access_token":"f14da3b8-b0b1-4f73-a5de-9bed637e0188","refresh_token_timeout":"20121222222222+0800"}
        return $result;
    }
    // 2018/2/26 获取速卖通所有店铺所有商品
	/*
    public function getAliexpressGoodsList(){
        //获取所有店铺所有商品列表
        //$this->CI->aliexpress->getAliexpressGoodsList();

        //速卖通平台 使用USD作为货币类型
        $sql_currency = "SELECT * FROM d_moneyrate WHERE name = 'USD' ";
        $rs_currency  = $this->db->query($sql_currency)->row_array();
        $moneyrate = $rs_currency['rate'];


        //判断生存期限仅十个小时的access_token是否过期   Ali-M-Coser  id 56 测试
        $sql = "SELECT * FROM d_shop WHERE platfromname = 'aliexpress' AND id = 56 AND agent_visit=0   ORDER BY id DESC ";
        $rs = $this->db->query($sql)->result_array();
        foreach($rs as $k_shop=>$v_shop){
            $time = time();
            if ($time >(int)$v_shop['access_timeout']) {
                //重新获取access_token，并更新 获取数据以最新access_token为准，不然获取不到
                $arr_access_token = $this->getAccessToken($v_shop['refresh_token'], $v_shop['appkey'], $v_shop['appsecret']);
                $data = "";
                $data['access_timeout'] = time() + $arr_access_token['expires_in'];
                $data['access_token'] = $arr_access_token['access_token'];
                $this->db->update('d_shop',$data," id = '".$v_shop['id']."'");
                $v['access_token'] = $data['access_token'];
            }
            //获取商品列表
            $appKey = $v_shop['appkey'];
            $appScret =$v_shop['appsecret'] ;
            $access_token = $v_shop['access_token'];
           
            $arr_sale_status = array("onSelling","offline","auditing","editingRequired");
            //销售循环 begin
            foreach($arr_sale_status as $k_sale=>$v_sale){
                //获取签名
                $api_relative_path = 'param2/1/aliexpress.open/api.findProductInfoListQuery' . '/' . $appKey;
                $arr_param = array('currentPage' =>1, 'pageSize' =>1, 'productStatusType' =>$v_sale,'access_token' => $access_token);
                $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
                //获取api签名结束
                //根据签名获取商品数据
                $request_url = $this->urlApi . "api.findProductInfoListQuery/" .$appKey;
                $data = 'currentPage=1&pageSize=1&productStatusType='.$v_sale.'&access_token=' .$access_token . '&_aop_signature=' . $sign;
                $result = $this->sendCurlPostRequest($request_url, $data);
                if(isset($result['success'])&&$result['success']==1){
                    $page_num = (int) ceil($result['productCount'] / 50);
                    for ($i = 1;$i <= $page_num; $i++) {
                        //获取签名
                        $api_relative_path = 'param2/1/aliexpress.open/api.findProductInfoListQuery' . '/' . $appKey;
                        $arr_param = array('currentPage' =>$i, 'pageSize' =>50, 'productStatusType' =>$v_sale,'access_token' => $access_token);
                        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
                        //获取api签名结束
                        //根据签名获取商品数据
                        $request_url = $this->urlApi . "api.findProductInfoListQuery/" .$appKey;
                        $data = 'currentPage='.$i.'&pageSize=50&productStatusType='.$v_sale.'&access_token=' .$access_token . '&_aop_signature=' . $sign;
                        $results = $this->sendCurlPostRequest($request_url, $data);
                        //根据商品id查询 商品sku等信息
                        foreach($results['aeopAEProductDisplayDTOList'] as $k_product=>$v_product){
                            //api签名  调用商品id接口获取该商品的更多信息
                            $api_rela_path = 'param2/1/aliexpress.open/api.findAeProductById' . '/' . $appKey;
                            $ary_param = array('productId'=>$v_product['productId'], 'access_token' => $access_token);
                            $receiner_sign = $this->getApiSign($api_rela_path, $appKey, $appScret, $ary_param);
                            //获取api签名结束
                            //调用商品id接口获取该商品的更多信息
                            $req_url = $this->urlApi . "api.findAeProductById/" .$appKey;
                            $url_data = 'productId='.$v_product['productId'].'&access_token=' .$access_token . '&_aop_signature=' . $receiner_sign;
                            $rs_product_sku = $this->sendCurlPostRequest($req_url, $url_data); //单个商品信息，数组格式
                            if(count($rs_product_sku['aeopAeProductSKUs'])>0){
                                foreach($rs_product_sku['aeopAeProductSKUs'] as $k_sku=>$v_sku){
                                    if(!$v_sku['skuCode']){
                                        continue;
                                    }
                                    $gmt_datetime = substr($v_product['gmtCreate'],0,14);
                                    $tmp_datetime = substr($gmt_datetime,0,4)."-".substr($gmt_datetime,4,2)."-".substr($gmt_datetime,6,2)." ".substr($gmt_datetime,8,2).":".substr($gmt_datetime,10,2).":".substr($gmt_datetime,12,2);
                                    $arr_ins['gmtCreate'] = $tmp_datetime;
                                    $tmp_datetime = strtotime($tmp_datetime)+8*60*60;
                                    $bj_datetime  = date("Y-m-d H:i:s",$tmp_datetime);
                                    $arr_product = array();
                                    $arr_product['types'] = $k_sale; //销售类型
                                    $arr_product['platform_id'] = $v_shop['platfrom'];
                                    $arr_product['shopid'] = $v_shop['id'];
                                    $arr_product['shopname'] = $v_shop['name'];
                                    $arr_product['goods_sku'] = $v_sku['skuCode'];
                                    $arr_product['sales_sku'] = $v_sku['skuCode'];
                                    $arr_product['moneytype'] = $v_sku['currencyCode'];
                                    $arr_product['moneyrate'] = $moneyrate;
                                    $arr_product['price'] = $v_sku['skuPrice']*$moneyrate;
                                    $arr_product['original_price'] = $v_sku['skuPrice'];
                                    $arr_product['qty'] = $v_sku['ipmSkuStock']; //当前可用库存
                                    $arr_product['sales_time'] = $bj_datetime;
                                    $arr_product['product_id'] = $v_product['productId'];
                                    $arr_product['product_link'] = 0;
                                    $arr_product['instime'] = time();
                                    $arr_product['skuId']=$v_sku['id'];

                                    $sql_goods  = "SELECT * FROM db_goods WHERE goods_sku = '{$v_sku['skuCode']}' ";
                                    $rs_goods   = $this->db->query($sql_goods)->row_array();
                                    if(count($rs_goods)>0){
                                        $arr_product['goods_id'] = $rs_goods['goods_id'];
                                        $arr_product['parent_sku'] = $rs_goods['goods_parent_sku'];
                                        $arr_product['goods_name'] = $rs_goods['goods_name'];
                                    }

                                    //判断是否存在
                                    $sql_plat_product = "SELECT * FROM db_platform_productlist WHERE shopid = '{$v_shop['id']}' AND product_id = '{$v_product['productId']}' and skuId = '{$v_sku['id']}' ";
                                    $rs_plat_product  = $this->db->query($sql_plat_product)->row_array();
                                    if(count($rs_plat_product)>0){
                                            $this->db->update("db_platform_productlist",$arr_product," id = '".$rs_plat_product['id']."'");
                                    }else{
                                            $this->db->insert("db_platform_productlist",$arr_product);
                                    }
                                    //print_r($arr_product);exit;


                                }
                            }

                        }

                    }
                }else{
                    if($result['error_code']==401){  //判断授权
                        echo $result['error_message'];exit;
                    }
                }


            } //销售状态循环 end


        }


    }*/
	
	//获取店铺商品 方法结束
    //更新在线店铺商品的价格信息
    public function updGoodsPrice($shopid,$price,$product_id,$skuId){
        $sql = "SELECT * FROM d_shop WHERE id = {$shopid} ";
        $v_shop = $this->db->query($sql)->row_array();
        $time = time();
        if ($time >(int)$v_shop['access_timeout']) {
            //重新获取access_token，并更新 获取数据以最新access_token为准，不然获取不到
            $arr_access_token = $this->getAccessToken($v_shop['refresh_token'], $v_shop['appkey'], $v_shop['appsecret']);
            $data = "";
            $data['access_timeout'] = time() + $arr_access_token['expires_in'];
            $data['access_token'] = $arr_access_token['access_token'];
            $this->db->update('d_shop',$data," id = '".$v_shop['id']."'");
            $v['access_token'] = $data['access_token'];
        }
        //获取商品列表
        $appKey = $v_shop['appkey'];
        $appScret =$v_shop['appsecret'] ;
        $access_token = $v_shop['access_token'];
        //获取签名
        $api_relative_path = 'param2/1/aliexpress.open/api.editSingleSkuPrice ' . '/' . $appKey;
        $arr_param = array('productId' =>$product_id,'skuId' =>$skuId,'skuPrice' =>$price,'access_token' => $access_token);
        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
        //获取api签名结束
        //根据签名获取商品数据
        $request_url = $this->urlApi . "api.editSingleSkuPrice /" .$appKey;
        $data = 'productId='.$product_id.'&skuId='.$skuId.'&skuPrice='.$price.'&access_token=' .$access_token . '&_aop_signature=' . $sign;
        $result = $this->sendCurlPostRequest($request_url, $data);
        if(isset($result['error_code'])&&$result['error_code']==401){  //判断授权
           return 401;
        }else{
            return $result['success']; // 1为修改成功，0未失败
        }

    }
    //更新在线店铺商品的库存信息
    public function updGoodsStock($shopid,$stock,$product_id,$skuId){
        $sql = "SELECT * FROM d_shop WHERE id = {$shopid} ";
        $v_shop = $this->db->query($sql)->row_array();
        $time = time();
        if ($time >(int)$v_shop['access_timeout']) {
            //重新获取access_token，并更新 获取数据以最新access_token为准，不然获取不到
            $arr_access_token = $this->getAccessToken($v_shop['refresh_token'], $v_shop['appkey'], $v_shop['appsecret']);
            $data = "";
            $data['access_timeout'] = time() + $arr_access_token['expires_in'];
            $data['access_token'] = $arr_access_token['access_token'];
            $this->db->update('d_shop',$data," id = '".$v_shop['id']."'");
            $v['access_token'] = $data['access_token'];
        }
        //获取商品列表
        $appKey = $v_shop['appkey'];
        $appScret =$v_shop['appsecret'] ;
        $access_token = $v_shop['access_token'];
        //获取签名
        $api_relative_path = 'param2/1/aliexpress.open/api.editSingleSkuStock' . '/' . $appKey;
        $arr_param = array('productId' =>$product_id,'skuId' =>$skuId,'ipmSkuStock' =>$stock,'access_token' => $access_token);
        $sign = $this->getApiSign($api_relative_path, $appKey, $appScret, $arr_param);
        //获取api签名结束
        //根据签名获取商品数据
        $request_url = $this->urlApi . "api.editSingleSkuStock/" .$appKey;
        $data = 'productId='.$product_id.'&skuId='.$skuId.'&ipmSkuStock='.$stock.'&access_token=' .$access_token . '&_aop_signature=' . $sign;
        $result = $this->sendCurlPostRequest($request_url, $data);
        if(isset($result['error_code'])&&$result['error_code']==401){  //判断授权
            return 401;
        }else{
            return $result['success']; // 1为修改成功，0未失败
        }

    }
    /*
     * 发送请求
     * @param  $url
     * @param $post_data
     */
    protected function sendCurlPostRequest($url,$post_data)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //post请求方式
        curl_setopt($ch,CURLOPT_POST,TRUE);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
        curl_setopt($ch,CURLOPT_TIMEOUT,300);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $response = curl_exec($ch);
        curl_close($ch);
        $response = json_decode($response,TRUE);
        return $response;
    }
    //速卖通交运回传相关运单号
    //@param  orderid 订单id号 db_order_list 或者去轮询查找该速卖通店铺的相关订单
    public function createSendGoodsOrderOnline(){
        $order_id = $this->CI->input->get('order_id'); //如果传入单个参数话,就只行该单个参数，否则执行相关循环
        //$order_id = "8765"; //测试
        //店铺相关操作
        $fileds = " id,appkey,appsecret,refresh_token,refresh_timeout,access_token,access_timeout ";
        $sql_shop = "SELECT $fileds FROM d_shop WHERE platfromname = 'aliexpress'  ORDER BY id DESC ";
        $rs_shop = $this->db->query($sql_shop)->result_array();
        $shop_where = " (";
        $arr_shop = array();
        if(count($rs_shop)>0){
            foreach($rs_shop as $k_shop=>$v_shop){
                $shop_where.= $v_shop['id'].",";
                $arr_shop[$v_shop['id']] = $v_shop;
            }
            $shop_where = trim($shop_where,",");
            $shop_where.=")";
        }else{
            exit("店铺不存在!");
        }
        //获取所有订单列表
        $where = " WHERE (order_status = 4 or order_status = 5) AND is_update_platform = 0 "; //4为已发货状态 is_update_platform为未与线上同步
        $where .= " AND shipping_name is not null AND shipping_number is not null ";
        if($order_id){
            $where.=" AND order_id = '{$order_id}' ";
        }
        $where.= " AND shopid in $shop_where ";
        //$where.=" limit 0,100 "; //可以限定执行一次获取多少条数据
        $sql_mabangorder = "SELECT order_id,shipping_name,shopid,tradeid,shipping_number FROM db_order_list ".$where;
        $rs_mabangorder = $this->db->query($sql_mabangorder)->result_array();
        //echo $sql_mabangorder;exit;
        if(count($rs_mabangorder)>0){
            //获取相关字段信息，然后创建线上订单
            $time=time(); //当前时间
            foreach($rs_mabangorder as $k=>$v){
                if(!$v['shipping_name']){
                    continue;
                }
                if(!$v['shipping_number']){
                    continue;
                }
                //验证授权以及数字签名来创建订单
                $arr_app_check = $arr_shop[$v['shopid']];
                if(!$arr_app_check['access_timeout']){
                    echo "未知错误";echo "<br/>";continue; //若该店铺并未配置相关信息，则继续循环
                }
                //判断生存期限仅十个小时的access_token是否过期，过期则通过refresh_token重新获取
                if ($time >(int)$arr_app_check['access_timeout']) {
                    //重新获取access_token，并更新 获取数据以最新access_token为准，不然获取不到
                    $arr_access_token = $this->getAccessToken($arr_app_check['refresh_token'], $arr_app_check['appkey'], $arr_app_check['appsecret']);
                    $data['access_timeout'] = time() + $arr_access_token['expires_in'];
                    $data['access_token'] = $arr_access_token['access_token'];
                    $this->db->where('id', $v['shopid']);
                    $this->db->update('d_shop',$data);
                    $access_token = $data['access_token'];
                }else{
                    $access_token = $arr_app_check['access_token'];
                }
                //$access_token = "dffb5ac6-a8d8-426c-bb40-b145a1a19a71";  //测试
                $appKey = $arr_app_check['appkey'];
                $appScret = $arr_app_check['appsecret'];
                //$url = "http://gw.api.alibaba.com:80/openapi/param2/1/aliexpress.open/api.createWarehouseOrder/9552279";
                //获取所有物流服务
                //获取签名
                /**
                $api_logistics_path = 'param2/1/aliexpress.open/api.listLogisticsService' . '/' . $appKey;
                $arr_param = array('access_token' => $access_token);
                $sign = $this->getApiSign($api_logistics_path, $appKey, $appScret, $arr_param);
                $request_url = $this->urlApi . "api.listLogisticsService/" .$appKey;
                $data = 'access_token=' .$access_token . '&_aop_signature=' . $sign;
                $rs_logistics = $this->sendCurlPostRequest($request_url, $data);
                foreach ($rs_logistics['result'] as $kkk=>$vvv){
                    echo "insert into db_aliexpress_logistics(recommendOrder,trackingNoRegex,minProcessDay,logisticsCompany,maxProcessDay,displayName,serviceName) value('{$vvv['recommendOrder']}','{$vvv['recommendOrder']}','{$vvv['trackingNoRegex']}','{$vvv['minProcessDay']}','{$vvv['logisticsCompany']}','{$vvv['displayName']}','{$vvv['serviceName']}');";
                    echo "<br/>";
                }
                exit; **/

                /**
                if($rs_logistics['success']){
                    echo 888;exit;
                }else{
                    echo 290;exit;
                }**/
                //var_dump($rs_logistics);exit;

                //拼接api签名相关参数 填写发货通知
                if($v['shipping_name']=="中邮上海挂号小包"){
                    $v['shipping_name'] = "中邮小包挂";
                }
                //查询物流key
                $sql_key = "SELECT * FROM db_order_express WHERE name = '{$v['shipping_name']}' ";
                $rs_key = $this->db->query($sql_key)->row_array();
                $api_relative_path = 'param2/1/aliexpress.open/api.sellerShipment'. '/' . $appKey;
                //测试 固定参数
                //$v['tradeid'] = "84870942185762";
                //$v['mailNo'] = "LM471826170CN";
                //$rs_key['aliexpress_express']="EMS_ZX_ZX_US";
                $sendType = "all"; //默认
                $arr_param =
                    array(
                        'serviceName' =>$rs_key['aliexpress_express'],  //必填
                        'logisticsNo' =>$v['shipping_number'], //必填  物流追踪号
                       // 'description' => "",//可选 备注(只能输入英文，且长度限制在512个字符。
                        'sendType' => $sendType,//必填  状态包括：全部发货(all)、部分发货(part)
                        'outRef' => $v['tradeid'], //交易订单号
                       // 'trackingWebsite' => "", //可选当serviceName=Other的情况时，需要填写对应的追踪网址
                        'access_token'=>$access_token
                    );
                $sign = $this->getApiSign($api_relative_path, $appKey, $appScret,$arr_param);
                //获取api签名结束
                //发送请求
                $request_url = $this->urlApi . "api.sellerShipment/" .$appKey;
                $sign_data ='serviceName='.$rs_key['aliexpress_express'].'&logisticsNo='.$v['shipping_number'].'&sendType='.$sendType.'&outRef='.$v['tradeid'].'&access_token='.$access_token.'&_aop_signature='.$sign;
                $result = $this->sendCurlPostRequest($request_url, $sign_data);
                //var_dump($result);exit;
                if($result['success']==true){
                    $this->db->where('order_id',$v['order_id']);
                    $arr_plat['is_update_platform']=1;
                    $this->db->update('db_order_list',$arr_plat); //说明已经同步过

                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = 0;
                    $imgdata["types"] = 3;
                    $imgdata["content"] = '速卖通接口已发货,交易ID='.$v['tradeid'].",运单号=".$v["shipping_number"];
                    $imgdata["createUser"] ='auto';
                    $this->db->insert('db_goods_log', $imgdata);

                    //另一张日志表，记录与线上操作发货是否同步 db_onlineshop_log
                    $onlinedata["orderId"] = $v['order_id'];	//订单ID db_order_list
                    $onlinedata["updateTime"] = date("Y-m-d H:i:s");
                    $onlinedata["shippingNumber"] =$v["shipping_number"];
                    $onlinedata["shippingName"] =$v["shipping_name"];
                    $onlinedata["types"] = "速卖通同步线上发货操作"; //同步发货操作
                    $onlinedata["content"] = '速卖通接口发货操作同步,交易ID='.$v['tradeid'].",运单号=".$v["shipping_number"];
                    //$onlinedata["errorMessage"] = ;//成功则不填写
                    $this->db->insert('db_onlineshop_log', $onlinedata);
                }else{
                    if($result['error_code']=="15-2001"){
                        $this->db->where('order_id',$v['order_id']);
                        $arr_plat['is_update_platform']=1;
                        $this->db->update('db_order_list',$arr_plat); //说明已经同步过

                        //更新日志表db_goods_log
                        $imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list 就是tradeid
                        $imgdata["updatetime"] = date("Y-m-d H:i:s");
                        $imgdata["createUid"] = 0;
                        $imgdata["types"] = 3;
                        $imgdata["content"] = '速卖通接口已发货,交易ID='.$v['order_id'].",运单号=".$v["shipping_number"];
                        $imgdata["createUser"] ='auto';
                        $this->db->insert('db_goods_log', $imgdata);
                    }
                    //另一张日志表，记录与线上操作发货是否同步 db_onlineshop_log
                    if(isset($result['error_message'])){
                        $onlinedata["orderId"] = $v['order_id'];	//订单ID db_order_list
                        $onlinedata["updateTime"] = date("Y-m-d H:i:s");
                        $onlinedata["shippingNumber"] =$v["shipping_number"];
                        $onlinedata["shippingName"] =$v["shipping_name"];
                        $onlinedata["types"] = "速卖通同步线上发货操作"; //同步发货操作
                        $onlinedata["content"] = '速卖通接口发货操作同步,交易ID='.$v['tradeid'].",运单号=".$v["shipping_number"];
                        $onlinedata["errorMessage"] = $result['error_message'];
                        $this->db->insert('db_onlineshop_log', $onlinedata);
                    }
                }
                //print_r($result);exit;
               // return $result['success']; //返回true
            }
        }else{
            exit("暂时无订单可创建!");
        }

    }


}